package com.redpill.linpro.integration.db;

import javax.inject.Inject;

import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.redpill.linpro.integration.Account;
import com.redpill.linpro.integration.AccountRepository;
import com.redpill.linpro.integration.Amount;

@Repository
public class AccountRepositoryImpl implements AccountRepository {
	
	@Inject
	private SimpleJdbcTemplate jdbcTemplate;
	
	private final String GET_BALANCE_SQL = "select BALANCE from ACCOUNT where ACCOUNT_NUMBER = ?";
	
	private final String UPDATE_AMOUNT_SQL = "update ACCOUNT set BALANCE = BALANCE + ? where ACCOUNT_NUMBER = ?";
	
	private final String VALIDATE_ACCOUNT_EXIST_SQL = "select count(*) from ACCOUNT where ACCOUNT_NUMBER = ?";

	@Override
	public Amount getBalance(Account account) {
		int balance = jdbcTemplate.queryForInt(GET_BALANCE_SQL, account.getAccountNumber());
		return new Amount(balance);
	}

	@Override
	public void updateBalance(Amount balance, Account account) {
		jdbcTemplate.update(UPDATE_AMOUNT_SQL, balance.getAmount(), account.getAccountNumber());
	}

	public boolean isAccountExisting(final Account account) {
		int accountsWithAccountNumber = jdbcTemplate.queryForInt(VALIDATE_ACCOUNT_EXIST_SQL, account.getAccountNumber());
		return (accountsWithAccountNumber == 1 ? true : false);
	}
}
